<template>
  <div class="hv-flex">
    <a-dropdown
      v-model:visible="visible"
      :trigger="[trigger]"
      :overlayStyle="{
        position: 'fixed',
      }"
    >
      <div
        :class="['hv-color-dropdown-picker', 'hv-color-dropdown-picker-' + size]"
        :style="
          alpha > 0
            ? { backgroundColor: color, borderColor: borderColor }
            : { background: `url(${transparentImg})` }
        "
        @click.prevent
      ></div>
      <template #overlay>
        <hv-color-picker :color="color" :format="format" @change="change" />
      </template>
    </a-dropdown>
    <div class="hv-color-dropdown-color-preview" v-if="colorPreviewVisible">
      {{ color }}
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import ColorPicker from "./ColorPicker.vue";
import ColorPickerUtil from "./color-picker-util";
import transparentImg from "@/visual/assets/img/dashboard/transparent.png";

export default defineComponent({
  name: "ColorDropdownPicker",
  components: {
    hvColorPicker: ColorPicker,
  },
  props: {
    color: {
      type: String,
      default: "#000000",
    },
    format: {
      type: String,
      default: "rgba",
    },
    size: {
      type: String,
      default: "default",
    },
    trigger: {
      type: String,
      default: "click",
    },
    borderColor: {
      type: String,
      default: "#efefef",
    },
    colorPreviewVisible: {
      type: Boolean,
      default: true,
    },
  },
  emits: ["update:color", "change"],
  setup(props, { emit }) {
    const visible = ref(false);
    const alpha = ref<number>(1);

    const change = (value: any) => {
      emit("update:color", value);
      emit("change", value);
    };

    watch(
      () => props.color,
      () => {
        const color = ColorPickerUtil.parseColor(props.color, props.format);
        alpha.value = color.a;
      },
      { immediate: true }
    );

    return {
      change,
      visible,
      alpha,
      transparentImg,
    };
  },
});
</script>

<style lang="less" scoped>
.hv-color-dropdown-picker {
  border-radius: var(--hv-border-radius-base);
  cursor: pointer;
  border-width: var(--hv-border-width-base);
  border-style: var(--hv-border-style-base);
}

.hv-color-dropdown-picker-large {
  width: 40px;
  height: 40px;
}
.hv-color-dropdown-picker-default {
  width: 32px;
  height: 32px;
}
.hv-color-dropdown-picker-small {
  width: 22px;
  height: 22px;
}
.hv-color-dropdown-color-preview {
  margin-left: 10px;
  height: 22px;
  line-height: 22px;
}
</style>
